import createPersistedState from 'vuex-persistedstate'
import { updateGoodsNum } from '@/api/cart'
const cart = {
  namespaced: true,
  plugins: [
    createPersistedState()
  ],
  state () {
    return {
      // 购物车列表
      cartList: []
    }
  },
  getters: {
    // 被选中的商品列表
    checkedList (state) {
      return state.cartList.filter(item => item.isChecked)
    },
    // 商品总数
    totalGoodsNum (state) {
      return state.cartList.reduce((sum, item) => sum + item.goods_num, 0)
    },
    // 被选中的商品总数
    checkedTotalCount (state, getters) {
      return getters.checkedList.reduce((sum, item) => sum + item.goods_num, 0)
    },
    // 被选中的商品总价格
    checkedTotalPrice (state, getters) {
      return getters.checkedList.reduce((sum, item) => sum + item.goods_num * item.goods.goods_price_min, 0).toFixed(2)
    },
    // 购物车列表是否全选
    isCheckedAll (state) {
      if (!state.cartList || state.cartList.length === 0) {
        return false
      }
      return state.cartList.every((item) => { return item.isChecked })
    },
    // 获取购物车被选中的商品的 cartsId
    getCartsIds (state, getters) {
      if (getters.checkedList && getters.checkedList.length !== 0) {
        const cartsIds = getters.checkedList.map(item => item.id)
        return cartsIds
      }
      return null
    }
  },
  mutations: {
    // 修改购物车商品列表
    setCartList (state, payload) {
      state.cartList = payload
    },
    // 修改购物车商品被选中的列表
    setCartGoodsChecked (state, goodsId) {
      state.cartList.forEach((item) => {
        if (item.goods_id === goodsId) {
          item.isChecked = (!item.isChecked)
        }
      })
    },
    // 反转全选
    reverseCheckAll (state, isCheckedAll) {
      state.cartList.forEach(item => {
        item.isChecked = isCheckedAll
      })
    },
    // 修改购物车商品的数量
    modifyGoodsNum (state, body) {
      const { goodsId, goodsNum } = body
      const goods = state.cartList.find(item => item.goods_id === goodsId)
      goods.goods_num = goodsNum
    }
  },
  actions: {
    // 修改购物车商品列表
    setCartListAction (context, payload) {
      context.commit('setCartListAction', payload)
    },
    // 修改购物车商品列表
    setCartGoodsCheckedAction (context, goodsId) {
      context.commit('setCartGoodsChecked', goodsId)
    },
    // 修改购物车商品的数量
    async modifyGoodsNumAction (context, body) {
      context.commit('modifyGoodsNum', body)
      await updateGoodsNum(body)
    },
    // 反转全选
    reverseCheckAllAction (context, payload) {
      context.commit('reverseCheckAll', payload)
    }
  }
}
export default cart
